package com.hellogood.work.evaluate.server.db;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class DBConnection {
	private Logger log = Logger.getLogger(this.getClass());
	private static DBConnection dbConn;

	private final String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
	// private final String driver = "com.mysql.jdbc.Driver";
	private String hostName = null;
	private String dbName = null;
	private String username = null;
	private String password = null;

	private DBConnection() {
		parseConfig();
	}

	public static DBConnection getInstance() {
		if (dbConn == null) {
			dbConn = new DBConnection();
		}
		return dbConn;
	}

	public Connection getConnection() {

		Connection conn = null;
		try {
			Class.forName(driver);
			String url = "JDBC:microsoft:SQLServer://" + hostName + ":1433; DatabaseName=" + dbName + ";SelectMethod=cursor;";
			// String url = "jdbc:mysql://" + hostName + "/" + dbName + "?user="
			// + username + "&useUnicode=true&characterEncoding=utf8";
			conn = DriverManager.getConnection(url, username, password);
			conn.setCatalog(dbName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			log.error("找不到数据库驱动" + e.getMessage());
		} catch (SQLException e) {
			e.printStackTrace();
			log.error("数据库连接错误" + e.getMessage());
		}
		return conn;
	}

	private void parseConfig() {
		Properties prop = new Properties();
		try {
			String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "config.properties";
			URL url = this.getClass().getResource(path);
			url = this.getClass().getResource("/config.properties");
			prop.load(url.openStream());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		hostName = prop.getProperty("host");
		username = prop.getProperty("username");
		password = prop.getProperty("password");
		dbName = prop.getProperty("dbname");
	}

	public static void main(String[] args) {
		DBConnection dbc = new DBConnection();
		dbc.parseConfig();
	}
}
